package com.sd.repay.task;

import com.sd.repay.common.Constants;
import com.sd.repay.pojo.PayOrder;
import com.sd.repay.service.PayOrderService;
import com.sd.repay.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 根据交易状态通知业务处理
 */
@Component
public class NotifyPayOrderResultTask {

    private static Logger log = LoggerFactory.getLogger(NotifyPayOrderResultTask.class);

    @Autowired
    private PayOrderService payOrderService;

    public void executePayOrderNotify() {
        log.info("--------查询需要通知的交易订单记录---------");
        try {
            List<PayOrder> unNotifyOrders = payOrderService.getNeedNotifyPayOrder();
            String orderNo;
            String orderStatus;
            String notifyResult;
            log.info("--------需要通知的交易订单记录条数-------------" + unNotifyOrders.size());

            for (PayOrder order : unNotifyOrders) {

                orderNo = order.getOrderNo();
                orderStatus = order.getTransStatus();
                //业务通知
                try {
                    notifyResult = payOrderService.payOrderCallBack(orderNo);
                    log.info("交易订单号" + orderNo + "业务通知结果,notifyResult=" + notifyResult);
                    if ("SUCCESS".equals(notifyResult)) {
                        int updateRow = payOrderService.updatePayOrderNotifyNum(orderNo);
                        log.info("交易订单号" + orderNo + "业务通知成功，通知次数加一影响的行数" + updateRow);

                        updateRow = payOrderService.updatePayOrderNotifyStatus(orderNo, Constants.IS_NOT_NEED_NOTIFY);
                        log.info("交易订单号" + orderNo + "业务通知成功，改为不需要通知状态影响的行数" + updateRow);
                    }
                } catch (Exception e) {
                    log.info("交易订单号" + orderNo + "业务通知异常" + e);
                    e.printStackTrace();
                    continue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("-----------交易订单业务分发通知任务完成--------------");
        WebUtil.removeBlockTaskBySpringId(WebUtil.getClassSimpleName(this.getClass()));
    }
}
